//
//  LRSRoomViewController.swift
//  LaiLang
//
//  Created by David on 2017/2/19.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

let LRSCreateRoomApiName = "createroom"
let LRSCloseRoomApiName = "closeroom"

class LRSRoomViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    override var preferredStatusBarStyle: UIStatusBarStyle{
        get{
            return .lightContent
        }
    }
    
    var playerTable: UICollectionView!
    var itemWidth: CGFloat!
    
    var playerSFData: NSArray?
    
    var playerView: UIView!
    var playerCard: LRSPlayerCard!
    
    var roomIDLabel: UILabel!
    var roomID: Int?
    func setRoomID(_ i: Int?){
        roomID = i
        if roomIDLabel == nil {
            return
        }
        roomIDLabel.text = "房间号: "
        if i == nil{
            return
        }
        
        roomIDLabel.text! += "\(i!)"
    }
    
    var loadingView: LLFullScreenLoading!
    
    var numOfPlayer: Int?
    var gameMethod: Int?
    
    var playerState: [Int]?
    
    convenience init(numOfPlayer: Int, gameMethod: Int){
        self.init()
        self.numOfPlayer = numOfPlayer
        self.gameMethod = gameMethod
        
        playerState = []
        for _ in 0..<numOfPlayer{
            playerState?.append(0)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.groupTableViewBackground
        
        let headView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
        headView.backgroundColor = LRSThemeColor1
        view.addSubview(headView)
        
        let backBtn = UIButton(frame: CGRect(x: 8, y: 20, width: 44, height: 44))
        
        var attrStr = NSMutableAttributedString(string: "\u{e624}\n结束")
        attrStr.addAttribute(NSFontAttributeName, value: UIFont(name: "iconfont", size: 24)!, range: NSMakeRange(0, 1))
        attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 12), range: NSMakeRange(2, 2))
        attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.white, range: NSMakeRange(0, 4))
        backBtn.setAttributedTitle(attrStr, for: .normal)
        backBtn.titleLabel?.numberOfLines = 0
        headView.addSubview(backBtn)
        backBtn.addTarget(self, action: #selector(LRSRoomViewController.goBack), for: .touchUpInside)
        
        let infoLabel = UILabel(frame: CGRect(x: 64, y: 20, width: view.bounds.width - 80, height: 44))
        infoLabel.textColor = UIColor.white
        infoLabel.textAlignment = .right
        infoLabel.numberOfLines = 0
        
        let showStr = "请法官主持游戏\nLet the judge preside over the game"
        attrStr = NSMutableAttributedString(string: showStr)
        
        attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 16), range: NSMakeRange(0, 7))
        attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 12), range: NSMakeRange(7, showStr.characters.count - 7))
        infoLabel.attributedText = attrStr
        
        headView.addSubview(infoLabel)
        
        roomIDLabel = UILabel(frame: CGRect(x: 8, y: 68, width: view.bounds.width - 32, height: 20))
        roomIDLabel.textAlignment = .center
        roomIDLabel.textColor = UIColor.lightGray
        roomIDLabel.font = UIFont.systemFont(ofSize: 14)
        view.addSubview(roomIDLabel)
        roomIDLabel.text = "房间号: "
        
        
        
        itemWidth = (view.frame.width - 32)/4 - 8
        
        let collectLayout = UICollectionViewFlowLayout()
        collectLayout.itemSize = CGSize(width: itemWidth, height: itemWidth + 16)
        collectLayout.minimumInteritemSpacing = 8
        collectLayout.scrollDirection = .vertical
        
        
        playerTable = UICollectionView(frame: CGRect(x: 16, y: 92, width: view.bounds.width - 32, height: view.bounds.height - 92), collectionViewLayout: collectLayout)
        playerTable.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "player")
        playerTable.backgroundColor = UIColor.groupTableViewBackground
        playerTable.alwaysBounceVertical = true
        playerTable.delegate = self
        playerTable.dataSource = self
        view.addSubview(playerTable)
        
        playerView = UIView(frame: CGRect(x: 0, y: 64, width: view.bounds.width, height: view.bounds.height - 64))
        let blurBGView = UIVisualEffectView(frame: CGRect(x: 0, y: 0, width: playerView.bounds.width, height: playerView.bounds.height))
        blurBGView.effect = UIBlurEffect(style: .dark)
        playerView.addSubview(blurBGView)
        
        playerCard = LRSPlayerCard(frame: CGRect(x: 0, y: 0, width: view.bounds.width - 32, height: 400))
        playerCard.center = CGPoint(x: view.center.x, y: view.center.y - 64)
        playerCard.characterView.alpha = 1
        playerView.addSubview(playerCard)
        
        view.addSubview(playerView)
        playerView.alpha = 0
        
        loadingView = LLFullScreenLoading(frame: view.frame)
        view.addSubview(loadingView)
        loadingView.alpha = 0
        
        LRSCreateRoom()
    }
    
    func LRSCreateRoom(){
        
        if numOfPlayer != nil && gameMethod != nil{
            loadingView.alpha = 1
            let urlStr = "\(HJY_DOMAIN_NAME)/api/\(LRSCreateRoomApiName)?people=\(numOfPlayer!)&select=\(gameMethod!)"
            print(urlStr)
            let resq = URLRequest(url: URL(string: urlStr)!)
            URLSession.shared.dataTask(with: resq, completionHandler: { (data:Data?, resp:URLResponse?, err:Error?) in
                DispatchQueue.main.async {
                    self.loadingView.alpha = 0
                }
                if err != nil {
                    print(err!)
                    let alert = UIAlertController(title: "网络错误", message: nil, preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                    DispatchQueue.main.async {
                        self.present(alert, animated: true, completion: nil)
                    }
                    return
                }
                do{
                    print(String(data: data!, encoding: .utf8) ?? "data is not utf8 string")
                    let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                    let jsonData = jsonObj?.object(forKey: "data") as? NSDictionary
                    self.playerSFData = jsonData?.object(forKey: "shenfen") as? NSArray
                    
                    DispatchQueue.main.async {
                        self.playerTable.reloadData()
                        
                        self.setRoomID(jsonData?.object(forKey: "room") as? Int)
                        
                    }
                    
                    
                    
                }catch let ex{
                    let alert = UIAlertController(title: "网络错误", message: nil, preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                    DispatchQueue.main.async {
                        self.present(alert, animated: true, completion: nil)
                    }
                    
                    print(ex)
                }
            }).resume()
            
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if playerSFData != nil{
            return playerSFData!.count
        }
        return 0
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "player", for: indexPath)
        
        let iv = UIButton(frame: CGRect(x: 0, y: 0, width: itemWidth, height: itemWidth))
        iv.tag = indexPath.row+1
//        iv.backgroundColor = playerState![indexPath.row] == 0 ? UIColor.lightGray : LRSThemeColor1
        iv.setImage(#imageLiteral(resourceName: "LRS-player"), for: .normal)
        iv.adjustsImageWhenHighlighted = false
        cell.addSubview(iv)
        
        if playerState![indexPath.row] != 0 {
            let deadMask = UIView(frame: CGRect(x: 0, y: 0, width: itemWidth, height: itemWidth))
            deadMask.backgroundColor = UIColor(white: 0, alpha: 0.6)
            iv.addSubview(deadMask)
        }
        
        
        
        let touchGes = LRSTouch(target: self, action: #selector(LRSRoomViewController.killPlayer(ges:)))
//        touchGes.setValue(indexPath.row + 1, forKey: "tag")
        touchGes.tag = indexPath.row+1
        iv.addGestureRecognizer(touchGes)
        
        
        let longPress = LRSLongPress(target: self, action: #selector(LRSRoomViewController.peekPlayer(ges:)))
        longPress.minimumPressDuration = 0.3
        longPress.tag = indexPath.row+1
//        longPress.setValue(indexPath.row + 1, forKey: "tag")
        iv.addGestureRecognizer(longPress)
//        longPress.require(toFail: touchGes)
        touchGes.require(toFail: longPress)
        
//        iv.addTarget(self, action: #selector(LRSRoomViewController.peekPlayer(sender:)), for: .touchDown)
//        iv.addTarget(self, action: #selector(LRSRoomViewController.popPlayer), for: .touchUpInside)
//        iv.addTarget(self, action: #selector(LRSRoomViewController.popPlayer), for: .touchUpOutside)
        
        let textLabel = UILabel(frame: CGRect(x: 0, y: itemWidth, width: itemWidth, height: 16))
        textLabel.backgroundColor = LRSThemeColor2
        textLabel.textColor = UIColor.white
        textLabel.textAlignment = .center
        textLabel.font = UIFont.systemFont(ofSize: 14)
        textLabel.text = "\(indexPath.row+1)号玩家"
        cell.addSubview(textLabel)
        return cell
    }
    
    func goBack(){
        let alert = UIAlertController(title: "确定退出？", message: nil, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "不退出", style: .cancel, handler: nil))
        alert.addAction(UIAlertAction(title: "退出", style: .default, handler: {(action) in
            if self.roomID != nil{
                let urlStr = "\(HJY_DOMAIN_NAME)/api/\(LRSCloseRoomApiName)?room=\(self.roomID!)"
                URLSession.shared.dataTask(with: URL(string: urlStr)!).resume()
            }
            
            _ = self.navigationController?.popViewController(animated: true)
        }))
        self.present(alert, animated: true, completion: nil)
    }

    func peekPlayer(sender: UIButton){
        playerCard.id = sender.tag // 从1开始的
        playerCard.nickname = "\(sender.tag)号玩家"
        playerView.alpha = 1
        
        if playerSFData != nil{
            playerCard.shenfen = playerSFData?.object(at: sender.tag-1) as? String
        }
    }
    
    func peekPlayer(ges: LRSLongPress){
        
        print("longpress")
        if ges.state == .began{
            playerCard.id = ges.tag // 从1开始的
            playerCard.nickname = "\(ges.tag)号玩家"
            playerView.alpha = 1
            
            if playerSFData != nil{
                playerCard.shenfen = playerSFData?.object(at: ges.tag-1) as? String
            }
        }else if ges.state == .ended{
            playerView.alpha = 0
        }
        
    }
    
    func killPlayer(ges: LRSTouch){
//        let tag = ges.value(forKey: "tag") as! Int
        let alive = playerState![ges.tag - 1]
        
        let alert = UIAlertController(title: "\(ges.tag)号玩家\(alive == 0 ? "标记阵亡" : "取消标记")？", message: nil, preferredStyle: .actionSheet)
        alert.addAction(UIAlertAction(title: "关闭", style: .cancel, handler: nil))
        alert.addAction(UIAlertAction(title: alive == 0 ? "标记阵亡" : "取消标记", style: .destructive, handler: { (action) in
            print("kill \(ges.tag)")
            self.playerState?[ges.tag - 1] = alive == 0 ? 1 : 0
            self.playerTable.reloadData()
            self.judgeGame()
        }))
        present(alert, animated: true, completion: nil)
        
    }
    
    func judgeGame(){
        var langrenCount = 0
        var peopleCount = 0
        for i in 0..<numOfPlayer!{
            if playerState![i] == 0{
                let shenfen = playerSFData?.object(at: i) as? String
                
                if shenfen == "狼人" {
                    
                    langrenCount += 1
                }else{
                    peopleCount += 1
                }
                
                
            }
            
        }
        
        if langrenCount == 0{
            let alert = UIAlertController(title: "游戏结束", message: "平民获胜", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
            present(alert, animated: true, completion: nil)
        }
        
        if peopleCount == 0{
            let alert = UIAlertController(title: "游戏结束", message: "狼人获胜", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
            present(alert, animated: true, completion: nil)
        }
    }
    
    func popPlayer(){
        playerView.alpha = 0
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

class LRSLongPress: UILongPressGestureRecognizer{
    var tag: Int = 0
}

class LRSTouch: UITapGestureRecognizer {
    var tag: Int = 0
}
